package com.example.lenovo.asia5b.commodity.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.apkfuns.logutils.LogUtils;
import com.example.lenovo.asia5b.commodity.adapter.ClassifyMainTitAdapter;
import com.example.lenovo.asia5b.commodity.bean.ClassifyBean;
import com.wushi.lenovo.asia5b.R;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import app.BaseActivity;
import com.example.lenovo.asia5b.ui.DownloadPicture;
import com.example.lenovo.asia5b.ui.LoadingDalog;
import com.example.lenovo.asia5b.util.DensityUtil;
import com.example.lenovo.asia5b.util.ICallBack;
import com.example.lenovo.asia5b.util.JsonTools;
import com.example.lenovo.asia5b.util.Logic;
import com.example.lenovo.asia5b.util.Setting;

import static com.wushi.lenovo.asia5b.R.id.public_btn_left;

/**
 * 分类首页
 * Created by lenovo on 2017/6/23.
 */

public class ClassifyMainActivity extends BaseActivity  implements ICallBack{
    private FragmentTransaction transaction;
    private LoadingDalog loadingDalog;
    private LinearLayout ll_lay;
    private  List<ClassifyBean> lists;
    private ViewPager pager;
    private ClassifyMainTitAdapter adapter;
    private int page = 0;
    private HorizontalScrollView mHorizontalScrollView;//上面的水平滚动控件
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_classify_main);
        initView();
        userData();
    }

    public void initView() {
        loadingDalog = new LoadingDalog(this);
        F.id(R.id.public_title_name).text(getResources().getString(R.string.qbfl));
        F.id(public_btn_left).clicked(this);
        ll_lay = (LinearLayout)findViewById(R.id.ll_lay);
        pager = (ViewPager)findViewById(R.id.vp_class_main);
        pager.addOnPageChangeListener(new MyPagerOnPageChangeListener());
        mHorizontalScrollView = (HorizontalScrollView)findViewById(R.id.horizontalScrollView);

    }

    @Override
    public void onClick(View v) {
        Intent intent = null;
        switch (v.getId()) {
            case public_btn_left:
                finish();
                break;
            default:
                break;
        }
    }

    private Handler handler2 = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            JSONObject result= null;
            try {
                result = new JSONObject(msg.obj.toString());
            } catch (Exception e) {
            }
            int action = msg.what;
            if (action == 0) {
                if (null != result && result instanceof JSONObject) {
                    try {
                        JSONObject json = (JSONObject) result;
                        JSONArray title = json.getJSONArray("title");

                        lists = Logic.getCalssifyList(title);
                        addView();
                    } catch (Exception e) {
                        LogUtils.e("解析错误："+e);
                    }
                }
                loadingDalog.dismiss();
            }
        }
    };

    @Override
    public void logicFinish(Object result, int action) {
        Message msg = new Message();
        msg.what = action;
        msg.obj = result.toString();
        handler2.sendMessage(msg);
    }
    /**
     * 分类接口
     */
    public void userData() {
        loadingDalog.show();
        Map<String, String> formMap = new HashMap<String, String>();
        String url = Setting.ACTCATE;
        JsonTools.getJsonAll(this, url, formMap, 0);
    }

    public void addView() {
        int width  = DensityUtil.getScreenWidth(ClassifyMainActivity.this)/5;
        for(int i = 0; i<lists.size(); i++) {
            ClassifyBean bean =  lists.get(i);
            View hotSaleView =  LayoutInflater.from(ClassifyMainActivity.this).inflate(R.layout.item_classify_main_tit, null);
            hotSaleView.setLayoutParams(new LinearLayout.LayoutParams(width, ViewGroup.LayoutParams.WRAP_CONTENT));
            hotSaleView.setOnClickListener(new SelectItem(i));
            TextView txt_name = (TextView) hotSaleView.findViewById(R.id.txt_name);
            ImageView image_tit= (ImageView) hotSaleView.findViewById(R.id.image_tit);
            TextView txt_striping=  (TextView) hotSaleView.findViewById(R.id.txt_striping);
            DownloadPicture.loadNetwork(bean.getFileico(),image_tit);
            txt_name.setText(bean.getCat_name());
            if (i != 0) {
                txt_name.setTextColor(ContextCompat.getColor(ClassifyMainActivity.this,R.color.my_333));
                txt_striping.setVisibility(View.INVISIBLE);
            }
            txt_name.setVisibility(View.GONE);
            ll_lay.addView(hotSaleView);
        }
        adapter = new ClassifyMainTitAdapter(getSupportFragmentManager(), lists);
        pager.setAdapter(adapter);
        pager.setCurrentItem(page);
    }

    public class SelectItem implements View.OnClickListener{
        int id;
        public SelectItem(int id) {
            this.id = id;
        }
        @Override
        public void onClick(View v) {
//            select(id);
            pager.setCurrentItem(id);
        }
    }

    /**
     * 切换标题状态
     * @param id
     */
    public void select(int id) {
        for (int i = 0; i < ll_lay.getChildCount(); i++) {
            LinearLayout aa = (LinearLayout) ll_lay.getChildAt(i);
            TextView txt_name =(TextView) aa.getChildAt(1);
            txt_name.setTextColor(ContextCompat.getColor(ClassifyMainActivity.this,R.color.my_333));
            TextView txt_striping=  (TextView) aa.getChildAt(2);;
            txt_striping.setVisibility(View.INVISIBLE);
        }
        LinearLayout aa = (LinearLayout) ll_lay.getChildAt(id);
        TextView txt_name =(TextView) aa.getChildAt(1);
        txt_name.setTextColor(ContextCompat.getColor(ClassifyMainActivity.this,R.color.wathet3));
        TextView txt_striping=  (TextView) aa.getChildAt(2);;
        txt_striping.setVisibility(View.VISIBLE);
    }

    /**
     * ViewPager的PageChangeListener(页面改变的监听器)
     */
    private class MyPagerOnPageChangeListener implements ViewPager.OnPageChangeListener{

        @Override
        public void onPageScrollStateChanged(int arg0) {

        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
        }
        /**
         * 滑动ViewPager的时候,让上方的HorizontalScrollView自动切换
         */
        @Override
        public void onPageSelected(int position) {
            select(position);
            setCurrentTab(position);
        }
    }
//    ClassifyBean bean  = (ClassifyBean)adapterView.getAdapter().getItem(i);
//    Intent intent = new Intent(ClassifyMainActivity.this, ClassifyMainSonActivity.class);
//                intent.putExtra("catid",bean.cat_id);
//                intent.putExtra("catname",bean.cat_name);
//    startActivity(intent);

    public void setCurrentTab(int position){
        View txt_name =ll_lay.getChildAt(position);
        //获取屏幕宽度
        int screenWidth=getResources().getDisplayMetrics().widthPixels;
        //计算控件居正中时距离左侧屏幕的距离
        int middleLeftPosition=(screenWidth-txt_name.getWidth())/2;
        //正中间位置需要向左偏移的距离
        int offset=txt_name.getLeft()-middleLeftPosition;
        //让水平的滚动视图按照执行的x的偏移量进行移动
        mHorizontalScrollView.smoothScrollTo(offset,0);
    }
}